import json
import re
import traceback
from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse
# Create your views here.
from django.views import View
import logging

from ajia08.settings import settings
from ajia08.utils.qiniuyun.qiniu_storage import storage, QINIUYUN_URL
from lhc_order.models import Order

logger = logging.getLogger('django')
from ajia08.utils.views import LoginRequiredMixin
from django_redis import get_redis_connection
from VerificationCode_Webb.views import logger
from xiejian_user.models import User
from test_xianghaiyang.models import House, Area, HouseImage

"""注册"""
class RegisterView(View):
    """用户注册视图"""

    def post(self, request):
        """
        接收参数,保存到数据库
        :param request:
        {'mobile':手机号, 'phonecode':短信验证码.'password':密码}
        :return:{"errno": "0", "errmsg": "注册成功"}
        """
        # 1.接收参数
        json_dict = json.loads(request.body.decode())
        password = json_dict.get('password')
        mobile = json_dict.get('mobile')
        sms_code_client = json_dict.get('phonecode')
        # 2.校验参数
        if not all([password, mobile, sms_code_client]):
            return JsonResponse({"errno": 400,
                                 "errmsg": "缺少必传参数"})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 400,
                                 'errmsg': 'mobile格式有误'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'errno': 400, 'errmsg': 'password格式错误'})
        # 3.从redis中取出手机验证码并校验;
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        # 4.判断手机验证码是否有效,比对手机验证码
        if not sms_code_server:
            return JsonResponse({'errno': "4004", 'errmsg': '手机验证码已过期'})
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'errno': "4004", 'errmsg': '手机验证码有误'})
        # 5.保存用户信息
        try:
            user = User.objects.create_user(username=mobile,
                                            mobile=mobile, password=password)
        except Exception as e:
            logger.error(traceback.format_exc())
            return JsonResponse({'errno': "4001", 'errmsg': '保存到数据库有误'})
        # 6.状态保持
        # print(user)
        login(request, user)
        return JsonResponse({'errno': "0", 'errmsg': '注册成功'})


"""登入"""
"""实现退出登录逻辑"""
"""判断是否登入"""
class LoginView(View):

    def post(self, request):
        '''实现登录接口'''
        # 1.接收参数
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        password = dict.get('password')

        # 2.校验(整体 + 单个)
        if not all([mobile, password]):
            return JsonResponse({'code': 400,
                                 'errmsg': '缺少必传参数'})

        # 3.验证是否能够登录
        user = authenticate(username=mobile,
                            password=password)

        # 判断是否为空,如果为空,返回
        if user is None:
            return JsonResponse({'code': 400,
                                 'errmsg': '用户名或者密码错误'})
        # 4.状态保持
        login(request, user)
        # request.session.set_expiry()
        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response = JsonResponse({"errno": "0",
                             "errmsg": "登录成功"})
        response.set_cookie('username',
                        user.username,
                            max_age=3600 * 24 * 14)
        # 8.返回json
        return response

    def get(self, request):
        # print(request.session)
        v = request.session.get('username')
        # print(v)
        # print(request.user.username)
        if request.user.is_authenticated:
            return JsonResponse({"errno": "0",
                                 "errmsg": "已登录",
                                 "data": {"user_id":request.user.id,
                                     "name": request.user.username}})
        else:
            return JsonResponse({"errno": "4101",
                                 "errmsg": "未登录"})

    def delete(self, request):
        """实现退出登录逻辑"""
        # 清理 session
        logout(request)

        response =  JsonResponse({"errno": "0",
                             "errmsg": "已登出"})
        response.delete_cookie('username')
        return response


"""用户名修改"""
class UserNameView(LoginRequiredMixin, View):
    """用户名修改"""
    def put(self, request):
        # 接收参数
        data = json.loads(request.body.decode())
        name = data.get('name')
        print(type(name))
        if not name:
            return JsonResponse({'code': "4002",
                                 'errmsg': '缺少必传参数'})

        # 判断字符串是否含有中文(百度的资料)
        for ch in name:
            if u'\u4e00' <= ch <= u'\u9fff':
                return JsonResponse({'code': "4104",
                                 'errmsg': '非法用户名'})
        if (User.objects.all().filter(username=name)):
            return JsonResponse({'code': "4003",
                                 'errmsg': '用户名已存在'})

        # 保存到数据库
        try:
            request.user.username = name
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400,
                                 'errmsg': '修改用户名失败'})
        return JsonResponse({"errno": "0",
                             "errmsg": "修改成功"})


"""个人中心"""
class UserInfoView(LoginRequiredMixin, View):
    """个人中心"""
    def get(self, request):
        # print(QINIUYUN_URL)
        # 拼接图片地址
        avatar_url = QINIUYUN_URL + str(request.user.avatar)
        # print(avatar_url)
        info_data = {
            # "avatar_url": request.user.avatar.str(),  # 用户头像
            "avatar_url": avatar_url,  # 用户头像
            "create_time": request.user.date_joined.strftime('%Y-%m-%d %H:%M:%S'),  # 用户创建时间
            "mobile": request.user.mobile,  # 用户手机
            "name": request.user.username,  # 用户昵称
            "user_id": request.user.pk  # 用户id
        }
        # 返回响应
        return JsonResponse({"data": info_data,
                             "errmsg": "OK",
                             "errno": "0"})


"""上传头像"""
class UserAvatar(LoginRequiredMixin, View):
    def post(self, request):
        # 接收参数
        img = request.FILES.get("avatar", None)
        if img:
            # 利用七牛云提供的接口
            img_url = storage(img.read())
            avatar_url = QINIUYUN_URL+img_url
            # print(avatar_url)
            # print(img_url, type(img_url))
            request.user.avatar = img_url
            request.user.save()
            date = {"avatar_url": avatar_url}
            return JsonResponse({"data": date,
                                 "errno": "0",
                                 "errmsg": "头像上传成功"})
        else:
            return JsonResponse({"errno": "4002	",
                                 "errmsg": "无数据"})


"""我的房源"""
class MyHouseView(LoginRequiredMixin, View):
    def get(self, request):
        user_id = request.user.id
        houses = House.objects.filter(user=user_id)
        # houses = House.objects.filter(user=1) # 测试id为1的用户所拥有的房子
        list = []
        for house in houses:
            list.append({
                "address":house.address,
                "area_name":Area.objects.filter(id=house.area_id)[0].name,
                "ctime":house.create_time,
                "house_id":house.pk,
                "img_url":QINIUYUN_URL+str(house.index_image_url),
                "order_count":house.order_count,
                "price":house.price,
                "room_count":house.room_count,
                "title":house.title,
                "user_avatar":QINIUYUN_URL+str(request.user.avatar)
            })
        # print(list)
        return JsonResponse({"data":{"houses":list},
                             "errmsg":"ok",
                             "errno":"0"})


"""房屋详情页"""
class HomeDetailView(View):
    def get(self, request, house_id):
        house_id = house_id
        if request.user.is_authenticated:
            user_id = request.user.id
        else:
            user_id = -1
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({"errmsg": "无数据",
                                 "errno": "4002"})
        home_image_list = [] # 房屋图片列表
        facilities_list = [] # 设施信息id列表，如：[7, 8]
        home_comments_list = []

        for home_image in HouseImage.objects.filter(house_id=house_id):
            home_image_list.append(QINIUYUN_URL+str(home_image.url))
            # print(home_image_list)



        for facility_id in house.facility.all():
            facilities_list.append(facility_id.id)
        # print(facilities_list)

        for home_comments in Order.objects.filter(house_id=house_id):
            home_comments_list.append({"comment":home_comments.comment, # 该房屋的评论列表
                                       "ctime":home_comments.update_time, # 评论时间
                                       "user_name":User.objects.get(id=home_comments.user_id).username}) # 评论人昵称
        # print(home_comments_list)



        return JsonResponse({
            "data":{
                "house":{
                    "acreage":house.acreage, # 房屋面积
                    "address":house.address, # 房屋地址
                    "beds":house.beds, # 房屋床铺的配置
                    "capacity":house.capacity, # 房屋容纳的人数
                    "comments":home_comments_list, # 该房屋的评论列表
                    "deposit":house.deposit, # 房屋押金
                    "facilities":facilities_list, # 设施信息id列表，如：[7, 8]
                    "hid":house_id, # 房屋id
                    "img_urls":home_image_list, # 房屋图片列表
                    "max_days":house.max_days, # 最大入住天数，0表示不限制
                    "min_days":house.min_days,# 最少入住天数
                    "price":house.price, # 价格
                    "room_count":house.room_count, # 房间数目
                    "title":house.title, # 标题
                    "unit":house.unit, # 房屋单元，如：几室几厅
                    "user_avatar":QINIUYUN_URL+str(User.objects.get(id=house.user_id).avatar), # 该房屋所有者的头像
                    "user_id":str(User.objects.get(id=house.user_id).id), # 该房屋所有者的用户id
                    "user_name":str(User.objects.get(id=house.user_id).username), #该房屋所有者的昵称
                },
            "user_id":user_id},
            "errmsg":"ok",
            "errno":"0"})